package com.rc.saas.tenant.controller.tenant;

import com.github.pagehelper.PageInfo;
import com.rc.saas.tenant.base.TenantBaseController;

import com.rc.saas.tenant.base.WebPageInfo;
import com.rc.saas.tenant.common.utils.ExcelExportUtil;
import com.rc.saas.tenant.common.vo.TResponse;
import com.rc.saas.tenant.model.sms.TenantSms;
import com.rc.saas.tenant.model.sms.TenantSmsRecord;
import com.rc.saas.tenant.model.tenant.TenantOpenService;
import com.rc.saas.tenant.model.tenant.TenantOpenServiceExample;
import com.rc.saas.tenant.model.tenant.TenantUser;
import com.rc.saas.tenant.model.tenantOrder.TenantOrder;
import com.rc.saas.tenant.model.transfer.TenantTransfer;
import com.rc.saas.tenant.search.tenant.TenantSmsSearch;
import com.rc.saas.tenant.service.sms.TenantSmsRecordService;
import com.rc.saas.tenant.service.sms.TenantSmsService;
import com.rc.saas.tenant.service.tenant.TenantOpenServiceService;
import com.rc.saas.tenant.service.tenant.TenantOrderSerivce;
import com.rc.saas.tenant.service.tenant.TenantUserService;
import com.rc.saas.tenant.service.transfer.TenantTransferService;
import com.rc.saas.tenant.shiro.ShiroUtils;
import com.rc.saas.tenant.vo.sms.PrintSmsVo;
import com.rc.saas.tenant.vo.tenant.TenantOrderSearch;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;


import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/tenant/serviceType")
public class TenantServiceTypeController extends TenantBaseController {

    private static Logger logger = LogManager.getLogger(TenantServiceTypeController.class);
    @Autowired
    private TenantSmsRecordService tenantSmsRecordService;

    @Autowired
    private TenantSmsService tenantSmsService;

    @Autowired
    private TenantUserService tenantUserService;
    @Autowired
    private TenantOpenServiceService tenantOpenServiceService;
    @Autowired
    private TenantOrderSerivce tenantOrderSerivce;

    @Autowired
    private TenantTransferService tenantTransferService;

    /**
     * 跳转短信服务页面
     *
     * @return
     */
    @RequestMapping(value = "/tenantSmsIndex", method = RequestMethod.GET)
    public String tenantSmsPage() {
        return "/templates/sms/tenantSms";
    }

    /**
     * 跳转页面
     *
     * @return
     */
    @RequestMapping(value = "/tenantIndex/{code}", method = RequestMethod.GET)
    public String tenantCardPage(Model model, @PathVariable("code") String code) {
        if (StringUtils.isBlank(code)) {
            return "/empty";
        }
        TenantUser user = ShiroUtils.getSessionUser();
        TenantUser findUser = tenantUserService.selectByPrimaryKey(user.getTenantUserId());
        TenantOrder tenantOrder = tenantOrderSerivce.selectByTypeCode(code, findUser.getTenantCode());

        TenantOpenServiceExample tenantOpenServiceExample = new TenantOpenServiceExample();
        tenantOpenServiceExample.createCriteria().andTenantCodeEqualTo(findUser.getTenantCode()).andServiceTypeCodeEqualTo(code);
        List<TenantOpenService> tenantOpenServices = tenantOpenServiceService.selectByExample(tenantOpenServiceExample);
        if (!CollectionUtils.isEmpty(tenantOpenServices)) {
            model.addAttribute("tenantOpenService", tenantOpenServices.get(0));
        } else {
            model.addAttribute("tenantOpenService", null);
        }
        model.addAttribute("tenantOrder", tenantOrder);
        model.addAttribute("code", code);

        if (tenantOrder != null) {
            if ("TRANSFERS".equals(tenantOrder.getServiceTypeCode()) && "1".equals(tenantOrder.getStatus())) {
                TenantTransfer tenantTransfer = tenantTransferService.selectByPrimaryKey(1l);
                model.addAttribute("tenantTransfer", tenantTransfer);
                return "templates/transfer/tenantTransfer";
            }
        }

        return "templates/tenant/openService/openService";
    }

    /**
     * 开通功能
     */
    @RequestMapping(value = "/toOpenService")
    @ResponseBody
    public TResponse toOpenService(TenantOrderSearch tenantOrderSearch) {
        TenantUser user = ShiroUtils.getSessionUser();
        TenantUser findUser = tenantUserService.selectByPrimaryKey(user.getTenantUserId());
        //  TenantOpenService tenantOpenService = tenantOpenServiceService.selectByTypeCode(findUser.getTenantCode(), ServiceTypeEnum.CARD.getCode());
        //  if (tenantOpenService != null) {
        //      if ("0".equals(tenantOpenService.getStatus())) {
        //          return TResponse.FAIL("已经开通了");
        //      }
        //  }
        try {
            TenantOrder tenantOrder = new TenantOrder();
            tenantOrder.setTenantCode(findUser.getTenantCode());
            String orderNum = "saas" + new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date())
                    + UUID.randomUUID().toString().substring(21);
            tenantOrder.setOrderNum(orderNum);
            tenantOrder.setServiceTypeCode(tenantOrderSearch.getServiceTypeCode());
            tenantOrder.setAmount(tenantOrderSearch.getAmount());
            tenantOrder.setEffectivePeriod(tenantOrderSearch.getEffectivePeriod());
            tenantOrder.setRemark("申请开通功能:" + tenantOrderSearch.getServiceTypeCode());
            tenantOrder.setStatus("0");
            tenantOrder.setOrderTime(new Date());
            tenantOrder.setCreatedBy(findUser.getLoginName());
            tenantOrder.setCreatedTime(new Date());
            tenantOrder.setLastUpdatedBy(findUser.getLoginName());
            tenantOrder.setLastUpdatedTime(new Date());
            tenantOrderSerivce.insertSelective(tenantOrder);
            return TResponse.SUCCESS();
        } catch (Exception e) {
            logger.error("toOpenService异常:", e);
            return TResponse.FAIL("操作失败！");
        }

    }


    //短信服务--短信记录 短信剩余量
    @RequestMapping(value = "/findTenantSmsList")
    @ResponseBody
    public WebPageInfo findTenantSmsList(TenantSmsSearch tenantSmsSearch) {
        TenantUser user = ShiroUtils.getSessionUser();
        TenantUser findUser = tenantUserService.selectByPrimaryKey(user.getTenantUserId());
        if (tenantSmsSearch.getOffset() == null) {
            tenantSmsSearch.setOffset(0);
        }
        if (tenantSmsSearch.getLimit() == null) {
            tenantSmsSearch.setLimit(20);
        }

        tenantSmsSearch.setTenantCode(findUser.getTenantCode());
        PageInfo<TenantSmsRecord> tenantSmsRecords = tenantSmsRecordService.selectBySearch(tenantSmsSearch);


        return new WebPageInfo(tenantSmsRecords.getList(), Long.valueOf(tenantSmsRecords.getTotal()).intValue());
    }

    // 短信服务--短信剩余量
    @RequestMapping(value = "/findTenantSms")
    @ResponseBody
    public TResponse findTenantSms() {
        TenantUser user = ShiroUtils.getSessionUser();
        TenantUser findUser = tenantUserService.selectByPrimaryKey(user.getTenantUserId());
        TenantSms tenantSms = tenantSmsService.selectByPrimaryKey(findUser.getTenantCode());
        TResponse tResponse = TResponse.SUCCESS();
        tResponse.put(tenantSms);
        return tResponse;
    }


    /**
     * 打印短信记录
     */
    @ResponseBody
    @RequestMapping("/exportSmsRecord")
    public void exportSmsRecord(TenantSmsSearch tenantSmsSearch, HttpServletResponse response) throws Exception {
        if (tenantSmsSearch.getCount() == 0 || tenantSmsSearch.getCount() == null) {
            tenantSmsSearch.setCount(tenantSmsSearch.getLimit());
        }
        if (tenantSmsSearch.getCount() > 10000) {
            tenantSmsSearch.setCount(10000);
        }

        //导出拼接开始条数
        tenantSmsSearch.setOffset(tenantSmsSearch.getLimit() * (tenantSmsSearch.getOffset() - 1));

        List<TenantSmsRecord> list = tenantSmsRecordService.exportSmsRecord(tenantSmsSearch);
        List<PrintSmsVo> printList = new ArrayList<>();
        for (TenantSmsRecord tenantSmsRecord : list) {
            PrintSmsVo printSmsVo = new PrintSmsVo(tenantSmsRecord);
            printList.add(printSmsVo);
        }
        ExcelExportUtil.downLoadExcel(response, printList, "短信记录", "短信记录");
    }


    /**
     * 更改云产品状态
     *
     * @return
     */
    @RequestMapping(value = "/updateOpenService", method = RequestMethod.POST)
    @ResponseBody
    public TResponse updateOpenService(TenantOpenService tenantOpenService) {
        try {
            tenantOpenServiceService.updateTenantAndOperator(tenantOpenService);

            return TResponse.SUCCESS();
        } catch (Exception e) {
            logger.error("更改云产品状态失败", e);
            return TResponse.FAIL("更改云产品状态失败");
        }
    }


}
